package com.jl.jtils.file;


import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiangli
 * 文件操作工具类
 */
public class FileUtils {

    public static void buildImgFile(BufferedImage bfi, String suffix, String fileName) {
        buildImgFile(bfi, suffix, new File(fileName));
    }

    public static void buildImgFile(BufferedImage bfi, String suffix, File outFile) {
        try {
            ImageIO.write(bfi, suffix, outFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<File> getAllFiles(String path) {
        File file = new File(path);
        return getAllFiles(file);
    }

    public static List<File> getAllFiles(File file) {
        List<File> result = new ArrayList<>();
        getFiles(file, result, null);
        return result;
    }

    public static List<File> getFiles(File file, List<FileType> fileTypes) {
        List<File> result = new ArrayList<>();
        getFiles(file, result, fileTypes);
        return result;
    }

    public static List<File> getFiles(String path, List<FileType> fileTypes) {
        File file = new File(path);
        return getFiles(file, fileTypes);
    }

    private static void getFiles(File file, List<File> result, List<FileType> fileTypes) {
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) {
                return;
            }
            for (File value : files) {
                if (value.isDirectory()) {
                    getFiles(value, result, fileTypes);
                } else {
                    checkAndAdd(value, result, fileTypes);
                }
            }
        } else {
            checkAndAdd(file, result, fileTypes);
        }
    }

    private static void checkAndAdd(File file, List<File> result, List<FileType> fileTypes) {
        String name = file.getName();
        String suffix = "";
        String separator = ".";
        if (name.lastIndexOf(separator) >= 0) {
            suffix = name.substring(name.lastIndexOf(".") + 1);
        }
        String contentType = new MimetypesFileTypeMap().getContentType(file);
        FileType fileType = FileType.mimeTypeOf(contentType, suffix);
        if (fileTypes.contains(fileType)) {
            result.add(file);
        }
    }

}
